﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BingVis.Common;

namespace BingVis.GoogleTransit
{
    public class TransitStopTimeLoader : TransitLoaderBase<ITransitStopTime>, ITransitStopTimeLoader
    {
        public IEnumerable<ITransitStop> Stops { get; private set; }

        public TransitStopTimeLoader(IGTFSFile file, IEnumerable<ITransitStop> stops)
            : base(file)
        {
            Stops = stops;
        }

        public override void ProcessItem(ICSVLine line)
        {
            //trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type
            //11278542-BUSS39-hbs39011-Weekday-03,8:20:00,8:20:00,74611,1,,0,0

            DateTime tmpArrival = new DateTime();
            DateTime tmpDeparture = new DateTime();
            if ( !DateTime.TryParse(line["arrival_time"], out tmpArrival) )
            {
                tmpArrival = ParseArrivalDepartureTime(line["arrival_time"]);
            }

            if (!DateTime.TryParse(line["departure_time"], out tmpDeparture))
            {
                tmpDeparture = ParseArrivalDepartureTime(line["departure_time"]);
            }

            var stop = Stops.FirstOrDefault(s => s.Id == line["stop_id"]);
            if (stop == null)
                // Didn't find a matching stop... Log?
                return;
            var result = TransitStopTime.FromStop(stop);
            result.TripId = line["trip_id"];
            result.Arrival = tmpArrival;
            result.Departure = tmpDeparture;
            result.Sequence = Int32.Parse(line["stop_sequence"]);
            result.HeadSign = line["stop_headsign"];

            Items.Add(result);
            OnItemLoaded(result);
        }

        private DateTime ParseArrivalDepartureTime(string p)
        {
            try
            {
                var vals = p.Trim(" \"".ToCharArray()).Split(":".ToCharArray());
                return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Int32.Parse(vals[0]) % 24, Int32.Parse(vals[1]), Int32.Parse(vals[2]));
            }
            catch
            {
                return new DateTime();
            }
        }
    }
}
